import React, { memo, useEffect, useState, useRef } from 'react'
import './style.less'
import { Space, Tree, Button, Modal, Flex, InputRef, Input } from 'antd'
import type { TreeProps } from 'antd/es/tree'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { HsAdminInput } from '@hs-admin/base-components'
import { handleButtonShow } from '@/utils/tools'
import { getPrefixList, editPrefixById, createPrefix, deletePrefixById, deleteFileByIds } from '@/api/operationCenter/docMaintain'
import DocMaintainList from './List'
import Fileupload from '@/components/flie/Fileupload'
import ResolveFileList from '@/components/flie/ResolveFileList'
import { message } from '@hs-admin/utils'

const DocMaintain: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [treeData, settreeData]: any = useState([])
  const [fileId, setfileId]: any = useState([])
  const [treeid, settreeid]: any = useState(null)
  const [searchValue, setsearchValue]: any = useState('')
  const [searchNewValue, setsearchNewValue]: any = useState('')
  const [addDocmtValue, setaddDocmtValue]: any = useState('')
  const [treeState, setTreeState]: any = useState('')
  const ListRef = useRef<any>(null)
  const inputRef = useRef<InputRef>(null)
  const onSelect: TreeProps['onSelect'] = (selectedKeys) => {
    settreeid(selectedKeys[0])
  }

  const operate = (params: any, nodeData: any, e: any) => {
    inputRef.current!.focus({
      cursor: 'end'
    })
    e.stopPropagation() //阻止事件冒泡
    setTreeState(params)
    settreeid(nodeData.id)

    if (params === 'del') deletefix(nodeData.id)

    if (params === 'edit') setaddDocmtValue(nodeData.title)
  }
  function PrefixList() {
    getPrefixList({}).then((res: any) => {
      const tree = filterFileList(res)
      settreeData(tree)
      if (treeid) return

      if (res) settreeid(res[0].id)
    })
  }

  const getFile = () => {
    setsearchNewValue(searchValue)
  }
  const adddomtList = (value: any) => {
    setaddDocmtValue(value)
  }

  const adddomt = () => {
    if (treeState == 'edit' && addDocmtValue) {
      editPrefix() //修改目录
      setTreeState('')
    } else {
      // 否则就是创建
      if (addDocmtValue) {
        createfix() //创建目录
        setTreeState('')
      } else {
        message.warning('请输入目录名称')
      }
    }
  }

  // 修改目录
  function editPrefix() {
    return editPrefixById(treeid, { name: addDocmtValue }).then((res: any) => {
      if (res) {
        message.success('操作成功')

        setaddDocmtValue('')

        PrefixList()
      }
    })
  }

  // 新增目录
  function createfix() {
    const params: any = {
      name: addDocmtValue
    }
    if (treeState === 'add') {
      params.pid = treeid
    }
    createPrefix(params).then((res: any) => {
      if (res) {
        message.success('操作成功')

        setaddDocmtValue('')

        PrefixList()
      }
    })
  }

  /**
   * 递归处理 tree 数据
   * @param list tree 源数据
   */
  const filterFileList = (list: any, leval?: any) => {
    if (leval) {
      leval++
    } else {
      leval = 1
    }

    const array: any = []

    list?.forEach((element: any) => {
      element.leval = leval

      element.title = element.label

      element.key = element.id

      if (element.children && element.children.length) element.children = filterFileList(element.children, leval)

      array.push(element)
    })

    return array
  }

  // 删除目录
  function deletefix(id: any) {
    return deletePrefixById(id).then((res: any) => {
      if (res) {
        message.success(res.msg)

        reset()

        PrefixList()
      }
    })
  }

  //上传确定
  function handleOk() {
    setIsModalOpen(false)
    ListRef.current.initPage()
    setfileId([])
  }

  const handleUploadSuccess = (file: any) => setfileId((arr: any) => [...arr, file.id])

  // 表单modal-文件删除
  const Filedelect = (e: any) => {
    setfileId(fileId.filter((id: any) => id !== e.value))
    deleteFileById(e.value)
  }

  //删除对应目录的文档
  function deleteFileById(id: any) {
    deleteFileByIds({ ids: [id] }).then((res: any) => {
      if (res) {
        message.success('操作成功')
        if (!isModalOpen) {
          ListRef.current.getFileByIds()
        }
      }
    })
  }

  function reset() {
    settreeid(null)
    setsearchValue('')
    setsearchNewValue('')
    setaddDocmtValue('')
    setTreeState('')
    setIsModalOpen(false)
    setfileId([])
  }

  useEffect(() => PrefixList(), [])

  function rednerIcon(nodeData: any): React.ReactNode {
    return (
      <Flex align="center" justify="space-between">
        <span className="datatitle">{nodeData.title}</span>
        <Space className="lefticon">
          {nodeData.leval !== 3 && handleButtonShow('datashop.data_document.update') && <PlusOutlined onClick={(e) => operate('add', nodeData, e)} />}
          {handleButtonShow('datashop.data_document.update') && <DeleteOutlined onClick={(e) => operate('del', nodeData, e)} />}
          {handleButtonShow('datashop.data_document.update') && <EditOutlined onClick={(e) => operate('edit', nodeData, e)} />}
        </Space>
      </Flex>
    )
  }
  return (
    <div className="docMaintain-page-wrapper">
      <div className="docMaintain__left w-230px">
        <div className="docmet">文档目录</div>

        <Tree className="pb-10px" showIcon onSelect={onSelect} treeData={treeData} titleRender={(nodeData) => rednerIcon(nodeData)} />
        {handleButtonShow('datashop.data_document.update') && (
          <Space>
            <Input ref={inputRef} placeholder="请输入" value={addDocmtValue} onChange={(e: any) => adddomtList(e.target.value)} />
            <Button className="w-44px text-xs" size="small" type="primary" onClick={adddomt}>
              {treeState === 'edit' ? '保存' : '添加'}
            </Button>
            {treeState === 'edit' && (
              <Button
                className="w-44px text-xs"
                size="small"
                onClick={() => {
                  setTreeState('')
                  setaddDocmtValue('')
                }}>
                取消
              </Button>
            )}
          </Space>
        )}
      </div>
      <div className="docMaintain__right">
        <Space className="top">
          <HsAdminInput
            placeholder="请输入"
            defaultValue={searchValue}
            onChange={(e: any) => setsearchValue(e.target.value)}
            onPressEnter={getFile}
          />
          <Button onClick={getFile} type="primary">
            搜索
          </Button>
        </Space>
        <div className="mid">
          {handleButtonShow('datashop.data_document.create') && (
            <Button type="primary" onClick={() => setIsModalOpen(true)}>
              上传
            </Button>
          )}
        </div>
        <DocMaintainList ref={ListRef} id={treeid} searchValue={searchNewValue}></DocMaintainList>
      </div>
      <Modal centered title={'文档上传'} open={isModalOpen} closeIcon={null} footer={null}>
        <Fileupload
          success={(e) => handleUploadSuccess(e)}
          params={{ file_prefix_id: treeid, creator: '' }}
          name="file"
          accept=".rar,.zip,.doc,.docx,.xlsx,.pdf"></Fileupload>
        <div className="pt-15px">
          <ResolveFileList ids={fileId} edit={true} delect={Filedelect}></ResolveFileList>
        </div>
        <Flex justify="end">
          <Button onClick={handleOk} type="primary">
            确定
          </Button>
        </Flex>
      </Modal>
    </div>
  )
}

export default memo(DocMaintain)
